import axios from "axios";

export function getList(addr) {
  return axios({
    method: "GET",
    url: "api/list",
    params: {
      svrAddr: addr,
    },
  });
}

async function wakeupEdge(svrAddr, edgeId, localPort) {
  return axios.put("api/edge/", { edgeId, localPort, svrAddr });
}
export function getEdgeTunnel(edgeID){
  return axios.get("api/edge?edgeID=" + edgeID)
}
export function removeEdge(edgeId) {
  return axios({ method: "DELETE", url: "api/edge/" + edgeId });
}

export function beginTunnel(EdgeID, TargetIP, Port, NetType,LocalPort) {
  return axios.put("api/begin/", { EdgeID, TargetIP, Port, NetType,LocalPort });
}

export function closeTunnel(edgeID, targetIP, targetPort) {
  return axios.post("api/remove/", { edgeID, targetIP, targetPort });
}
function sleep(time) {
  return new Promise((resolve) => setTimeout(resolve, time));
}

export async function beginTunnelEx(EdgeID, TargetIP, Port, NetType, fun,localport) {
  for (let i = 0; i < 5; i++) {
    let res = await beginTunnel(EdgeID, TargetIP, Port, NetType,localport);
    if (res && res.data) {
      if (res.data.addr) {
        fun(res.data.addr);
        return;
      }
    }
    await sleep(2000);
  }
  fun("", "等待超时");
}

export async function wakeupEdgeEx(svrAddr, edgeId, localPort, callback) {
  let run = true;
  while (run) {
    let res = await wakeupEdge(svrAddr, edgeId, localPort);
    console.log("-----------result:", res);
    if (res && res.data && res.data.result) {
      if (res.data.result.state === "kcp ready") {
        if (callback) {
          callback(1, "隧道打通完成", true, res.data.result.localAddr);
        }
        return;
      } else if (!res.data.result.state) {
        callback(1, "错误", false, res.data.result.localAddr);
        return;
      } else if (
        res.data.result.state.indexOf("end") >= 0 ||
        res.data.result.state.indexOf("END") >= 0
      ) {
        callback(
          1,
          "已关闭，如果需要使用请重新开启隧道",
          false,
          res.data.result.localAddr
        );
        return;
      } else if (res.data.result.state.indexOf("kcp not launched") >= 0) {
        callback(
          1,
          "kcp没有建立成功，edge节点没有应答，请检查edge节点状态",
          false,
          res.data.localAddr
        );
        return;
      } else if (res.data.result.state.indexOf("begin") >= 0) {
        callback(0.2, "开始建立隧道", false, res.data.result.localAddr);
      }
      console.log("*************", res.data.result.state);
    } else {
      callback(1, "服务器没有返回", false);
      return;
    }
    await sleep(2000);
  }
}
